using System;
using System.Collections.Generic;
using System.IO;

namespace resx_utils
{

	public class resxsort
	{

		public static void Main(string[] args)
		{

			// get args
			bool isQuiet = false;
			bool isValid = true;
			string resx1File = null;
			string resx2File = null;

			for(int i = 0; i < args.Length; i++)
			{
				if (args[i].Equals("-quiet"))
					isQuiet = true;
				else if (resx1File == null)
					resx1File = args[i];
				else if (resx2File == null)
					resx2File = args[i];
				else
					isValid = false;
			}

			isValid &= (resx1File != null && resx2File != null);

			// Invalid usage
			if (!isValid)
			{
				Console.WriteLine("resxsort [-quiet] file1 file2 - transform .resx entries in file1 to sorted, tab delimited file2");
				return;
			}


			// check files
			if (Utils.VerifyExistance(resx1File))
			{
				// Do they want to overwrite file2 if it exists?
				if(File.Exists(resx2File) != isQuiet)
				{
					Console.Write("{0} exists.  Overwrite (y/n)? ", resx2File);
					string response = Console.ReadLine();
					response = response.ToLower().Trim();
					if (!(response.Length == 1 && response[0] == 'y'))
						return;
				}

				SortedDictionary<String, Object> nodes = Utils.CreateSortedDictionary(resx1File);
				int count = 0;
				using (StreamWriter sw = new StreamWriter(resx2File))
				{
					foreach (KeyValuePair<String, Object> node in nodes)
					{
						sw.WriteLine("{0}\t{1}", node.Key, node.Value.ToString());
						count++;
					}
				}
				if(!isQuiet)
				{
					Console.WriteLine("Wrote {0} lines to {1}.", count, resx2File);
				}

			}

		}

	}
}
